import { createBrowserRouter, RouterProvider } from "react-router-dom";

import { useEffect, useState, Suspense } from "react";
import { useSelector, useDispatch } from "react-redux";
import { generateRoutes } from "./utils/generatesRoutes";
import { getMenuApi } from "./api/users";
import { routes } from "@/router";
import { Spin } from "antd";
import { setMenu } from "./store/login/authSlice";
import { componentMap } from "./router/routerMap";

function App() {
  const { token } = useSelector((state: any) => state.auth);
  const [myrouter, setMyrouter] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const dispatch = useDispatch();

  useEffect(() => {
    let isMounted = true;
    const loadData = async () => {
      try {
        const response = await getMenuApi();
        const data = response.data || response;
        const menuData = Array.isArray(data) ? data : [data];

        if (isMounted) {
          dispatch(setMenu(menuData));
          const routers = generateRoutes(menuData);
          const myRoutes = [...routes];
          myRoutes[0].children = routers;
          
          // 设置第一个子路由为索引路由
          if (routers.length > 0) {
            // 创建一个新的索引路由指向第一个菜单项
            const firstRoutePath = routers[0].path;
            if (firstRoutePath && componentMap[firstRoutePath]) {
              myRoutes[0].children.unshift({
                index: true,
                element: componentMap[firstRoutePath]
              });
            }
          }
          setMyrouter(createBrowserRouter(myRoutes));
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };
    if (token) {
      loadData();
    } else {
      if (isMounted) {
        setMyrouter(createBrowserRouter(routes));
        setLoading(false);
      }
    }
    return () => {
      isMounted = false;
    };
  }, [token, dispatch]);

  if (loading) {
    return <Spin />;
  }

  if (myrouter) {
    return (
      <div className="App">
        <Suspense fallback={<Spin /> }>
          <RouterProvider router={myrouter} />
        </Suspense>
      </div>
    );
  }

  return null;
}

export default App;